﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace PIM_ATE.Mods
{
    class ClsDataCalibration
    {
        /// <summary>
        /// 保存交调测试校准信息ID, 主键
        /// </summary>
        public string ID { get; set; }
        /// <summary>
        /// 产品代码
        /// </summary>
        public string ProCode { get; set; }
        /// <summary>
        /// 测试设备编号
        /// </summary>
        public string EquID { get; set; }
        /// <summary>
        /// TX补偿值（线损）
        /// </summary>
        public double TXOffset { get; set; }
        /// <summary>
        /// RX补偿值（线损）
        /// </summary>
        public double RXOffset { get; set; }
        /// <summary>
        /// 标准件校准值
        /// </summary>
        public double ISOCalValue { get; set; }
        /// <summary>
        /// 校准时间
        /// </summary>
        public DateTime CalTime { get; set; }
        /// <summary>
        /// 有效性， 是否
        /// </summary>
        public bool Effective { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }
        /// <summary>
        /// F1
        /// </summary>
        public double TXL { get; set; }
        /// <summary>
        /// f2
        /// </summary>
        public double TXH { get; set; }
        /// <summary>
        /// F1
        /// </summary>
        public double RXL { get; set; }
        /// <summary>
        /// f2
        /// </summary>
        public double RXH { get; set; }
        /// <summary>
        /// f2
        /// </summary>
        public double STEP { get; set; }
        /// <summary>
        /// RX补偿值（线损）
        /// </summary>
        public double ProductOffset { get; set; }


        public void setValues(string sCode, DataRow drRow)
        {
            int n = 0;
            //ID = Convert.ToInt32(drRow[n++].ToString());
            ProCode = sCode.ToString();
            EquID = drRow[n++].ToString();
            TXOffset = Convert.ToDouble(drRow[n++].ToString());
            RXOffset = Convert.ToDouble(drRow[n++].ToString());
            ISOCalValue = Convert.ToDouble(drRow[n++].ToString());
            CalTime = DateTime.Parse(drRow[n++].ToString());
            Effective = PIMFunction.getBoolean(drRow[n++].ToString());
            Remark = drRow[n++].ToString();
            if (drRow[n].ToString() != "")
            TXL = Convert.ToDouble(drRow[n++].ToString());
            if (drRow[n].ToString() != "")
            TXH = Convert.ToDouble(drRow[n++].ToString());
            if (drRow[n].ToString() != "")
            RXL = Convert.ToDouble(drRow[n++].ToString());
            if (drRow[n].ToString() != "")
            RXH = Convert.ToDouble(drRow[n++].ToString());
            if (drRow[n].ToString() != "")
            STEP = Convert.ToDouble(drRow[n++].ToString());
            if (drRow[n].ToString() != "")
            ProductOffset = Convert.ToDouble(drRow[n++].ToString());
        }

        public string toValue()
        {
            string sValues = "";
            sValues += "'" + ProCode + "',";
            sValues += "'" + EquID + "',";
            sValues += "'" + TXOffset + "',";
            sValues += "'" + RXOffset + "',";
            sValues += "'" + ISOCalValue + "',";
            sValues += "'" + CalTime.ToString("yyyy-MM-dd HH:mm:ss") + "',";
            sValues += "'" + Effective + "',";
            sValues += "'" + Remark + "',";
            sValues += "'" + TXL + "',";
            sValues += "'" + TXH + "',";
            sValues += "'" + RXL + "',";
            sValues += "'" + RXH + "',";
            sValues += "'" + STEP + "',";
            sValues += "'" + ProductOffset + "'";
            return sValues;
        }

    }

    class ClsDataCalibrationBuilder
    {
        const string TABLE_NAME = "tb_PIMCalibration";
        string m_sConnect;
        string m_sProCode;
        string m_sEquID;

        #region static function

        public static bool createDataTable()
        {
            string strSql = "CREATE TABLE \"tb_PIMCalibration\" (" +
                            "\"ID\" INT NOT NULL identity(1,1) PRIMARY KEY, " +
                            "\"ProCode\" NVARCHAR(100) NOT NULL, " +
                            "\"EquID\" VARCHAR(100) NOT NULL, " +
                            "\"TXOffset\" VARCHAR(50) NOT NULL, " +
                            "\"RXOffset\" VARCHAR(50) NOT NULL, " +
                            "\"ISOCalValue\" VARCHAR(50) NOT NULL, " +
                            "\"CalTime\" DATETIME NOT NULL, " +
                            "\"Effective\" NVARCHAR(10) NOT NULL, " +
                            "\"Remark\" NVARCHAR(200), " +
                            "\"TXL\" VARCHAR(50), " +
                            "\"TXH\" VARCHAR(50), " +
                            "\"RXL\" VARCHAR(50), " +
                            "\"RXH\" VARCHAR(50), " +
                            "\"STEP\" VARCHAR(50), " +
                            "\"ProductOffset\" VARCHAR(50)" +
                            ");";
            try
            {
                MicroDBHelper.ExecuteNonQuery(strSql, null);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public static List<string> getColNames()
        {
            List<string> names = new List<string>();
            names.Add("ID");
            names.Add("ProCode");
            names.Add("EquID");
            names.Add("TXOffset");
            names.Add("RXOffset");
            names.Add("ISOCalValue");
            names.Add("CalTime");
            names.Add("Effective");
            names.Add("Remark");
            names.Add("TXL");
            names.Add("TXH");
            names.Add("RXL");
            names.Add("RXH");
            names.Add("STEP");
            names.Add("ProductOffset");
            return names;
        }

        public static List<string> getColNamesCN()
        {
            List<string> names = new List<string>();
            names.Add("ID");
            names.Add("产品代码");
            names.Add("设备ID");
            names.Add("TX差损");
            names.Add("RX补偿");
            names.Add("校准值");
            names.Add("校准时间");
            names.Add("有效性");
            names.Add("备注");
            names.Add("TXL");
            names.Add("TXH");
            names.Add("RXL");
            names.Add("RXH");
            names.Add("STEP");
            names.Add("ProductOffset");
            return names;
        }

        public static string getColNamesStr(int index = 2)
        {
            string[] lstCol = getColNames().ToArray();
            string sColNames = "";
            for (int i = index; i <= lstCol.Length - 1; i++)
            {
                if (i != lstCol.Length - 1)
                    sColNames += "[" + lstCol[i] + "],";
                else
                    sColNames += "[" + lstCol[i] + "]";
            }
            return sColNames;
        }

        public static string getColNamesCNStr(int index = 2)
        {
            string[] lstCol = getColNames().ToArray();
            string[] lstColCN = getColNamesCN().ToArray();
            string sColNames = "";
            for (int i = index; i <= lstCol.Length - 1; i++)
            {
                if (i != lstCol.Length - 1)
                    sColNames += "[" + lstCol[i] + "] as [" + lstColCN[i] + "],";
                else
                    sColNames += "[" + lstCol[i] + "] as [" + lstColCN[i] + "]";
            }
            return sColNames;
        }

        #endregion

        public ClsDataCalibrationBuilder(string alias)
        {
            m_sConnect = alias;
        }

        public void construct(string sProCode, string sEquID)
        {
            m_sEquID = sEquID;
            m_sProCode = sProCode;
        }

        public DataTable download(ref string error_info)
        {//下载当前版本的配置(需按时间排序)
            //if (m_sProCode == null || m_sProCode == "")
            //{//错误
            //    error_info = "当前实例未构造sProCode";
            //    return null;
            //}

            if (m_sProCode == null || m_sEquID == "")
            {//错误
                error_info = "当前实例未构造m_sEquID";
                return null;
            }

            try
            {
                string sColNames = getColNamesCNStr();
                SqlParameter param_code = new SqlParameter("@code", m_sProCode);
                SqlParameter param_equid = new SqlParameter("@id", m_sEquID);
                //string sSql = "select " + sColNames + " from " + TABLE_NAME + " where [Procode] = @code and [EquID] = @id order by [CalTime];";
                string sSql = "select " + sColNames + " from " + TABLE_NAME + " where [EquID] = @id order by [CalTime];";
                return MicroDBHelper.ExecuteDataTable(sSql,
                                                      new SqlParameter[] { param_code, param_equid },
                                                      m_sConnect);           
            }
            catch (Exception ex)
            {
                error_info = ex.Message;
                return null;
            }
        }

        public ClsDataCalibration downloadVaule(ref string error_info)
        {
            DataTable dt = download(ref error_info);
            if (dt == null || error_info != "" || dt.Rows.Count == 0) { return null; }
            ClsDataCalibration cal = new ClsDataCalibration();
            //获取最近的校准数据
            cal.setValues(m_sProCode, dt.Rows[dt.Rows.Count - 1]);
            return cal;
        }

        public bool update(ClsDataCalibration cal, ref string error_info)
        {
            try
            {
                string[] lstNames = getColNames().ToArray();
                int n = 3;
                string sParam = string.Format("[{0}] = '{1}', ", lstNames[n++], cal.TXOffset) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.RXOffset) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.ISOCalValue) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.CalTime.ToString("yyyy-MM-dd HH:mm:ss")) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.Effective) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.Remark) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.TXL) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.TXH) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.RXL) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.RXH) +
                                string.Format("[{0}] = '{1}', ", lstNames[n++], cal.STEP) +
                                string.Format("[{0}] = '{1}'", lstNames[n++], cal.ProductOffset);

                SqlParameter param_code = new SqlParameter("@code", cal.ProCode);
                SqlParameter param_equid = new SqlParameter("@id", cal.EquID);
                string sSql = "update " + TABLE_NAME + " set " + sParam + " where [Procode] = @code and [EquID] = @id";
                return MicroDBHelper.ExecuteNonQuery(sSql, new SqlParameter[] { param_code, param_equid }, m_sConnect) == 1;
            }
            catch (Exception ex)
            {
                error_info = ex.Message;
                return false;
            }
        }

        public bool upload(ClsDataCalibration cal, ref string error_info)
        {
            //if (m_sProCode == null || m_sProCode == "")
            //{//错误
            //    error_info = "当前实例未构造sProCode";
            //    return false;
            //}

            if (m_sProCode == null || m_sEquID == "")
            {//错误
                error_info = "当前实例未构造m_sEquID";
                return false;
            }

            try
            {
                using (var tran = MicroDBHelper.UseTransaction(IsolationLevel.RepeatableRead, m_sConnect))
                {
                    //SqlParameter param_code = new SqlParameter("@code", m_sProCode);
                    //SqlParameter param_equid = new SqlParameter("@id", m_sEquID);
                    //string sSql = "delete from " + TABLE_NAME + " where [ProCode] = @code and [EquID] = @id;";
                    //MicroDBHelper.ExecuteNonQuery(sSql, new SqlParameter[] { param_code, param_equid }, tran);

                    cal.EquID = m_sEquID;
                    cal.ProCode = m_sEquID;
                    //cal.ProCode = m_sProCode;
                    string sColNames = getColNamesStr(1);
                    string sSql = String.Format("insert into {0} ({1}) values ({2});", TABLE_NAME, sColNames, cal.toValue());
                    MicroDBHelper.ExecuteNonQuery(sSql, null, m_sConnect);
                    tran.MarkSuccess();
                }
            }
            catch (Exception ex)
            {
                error_info = ex.Message;
                return false;
            }

            return true;
        }
    }
}
